package developerworks.jetty6;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import org.json.JSONArray;
import org.mortbay.util.ajax.Continuation;

import developerworks.jetty6.UserServlet.Method;


import java.util.regex.Pattern;
import java.util.regex.Matcher;


public class Jabbify {
	  //private Collection<Continuation> pendingContinuations;
	  //private Collection<HttpSession> sessions;
	  private Hashtable<String, Domain> domain_hash;
	  
	  private Pattern pattern = Pattern.compile("https?://(?:www\\.)?([^/]*)([^#\\?]*)");
	  

	
	  public Jabbify() {
	    //pendingContinuations = new ArrayList<Continuation>();
	    //sessions = new ArrayList<HttpSession>();
		  domain_hash= new Hashtable<String, Domain>();
	  }
	  
	  
	  public static float match_version = 0.2f;
	  
	  public static Boolean filterVersion(HttpServletRequest req, HttpServletResponse res)  throws java.io.IOException  {
		  String version = req.getParameter("version");
		  float v = 0.0f;
		  if(version != null){
			  v = Float.valueOf(version).floatValue();
		  }
		  if(v >= match_version){
			  return true;
		  }else{
			  //print error
			  	System.out.println("Inadequate version("+v+") for "+ req.getRequestURL());
				/*System.out.println("  ua = "+req.getHeader("User-Agent"));
				HttpSession session = req.getSession(false);
				if(session != null){
					System.out.println("  si = "+session.getId());
				}else{
					System.out.println("  si = ?");
				}
				System.out.println("  rf = "+req.getHeader("Referer"));*/
				
				res.getWriter().print("alert('refresh for latest version of Jabbify!');");
				res.getWriter().print("throw('refresh for latest version');");
				res.getWriter().flush();
			  return false;
		  }
	  }
	  
	  
	  public static Method method(HttpServletRequest req){
			String method = req.getParameter("_method");
			if(method == null) method = req.getMethod();
			method = method.toLowerCase();
			if(method.compareTo("get") == 0) return Method.GET;
			if(method.compareTo("delete") == 0) return Method.DELETE;
			if(method.compareTo("put") == 0) return Method.PUT;
			return Method.POST;
		}
	  
}






